
import 'package:dart_serve_study/dart_serve_study.dart';

class DartServeStudyChannel extends ApplicationChannel {
  ManagedContext context;
  AuthServer _authServer;

  @override
  Future prepare() async {
    logger.onRecord.listen(
        (rec) => print("$rec ${rec.error ?? ""} ${rec.stackTrace ?? ""}"));
    // final AppConfig _config = AppConfig(options.configurationFilePath);
    // options.port = _config.port;
    ///=============================对系统文件进行配置的===================================
    final _config = ReadConfig(options.configurationFilePath);
    options.port = _config.port;
    final dataModel = ManagedDataModel.fromCurrentMirrorSystem();
    final persistentStore = PostgreSQLPersistentStore.fromConnectionInfo(
        _config.database.username,
        _config.database.password,
        _config.database.host,
        _config.database.port,
        _config.database.databaseName);
    context = ManagedContext(dataModel, persistentStore);
    ///=============================对系统文件进行配置的===================================
    final delegate = ManagedAuthDelegate<User>(context,
        tokenLimit: 20); //tokenLimit 用于限制token的长
    // ; //授权管理度
    _authServer = AuthServer(delegate); //获取到的授权服务类
  }

  @override
  Controller get entryPoint => Router()
    ..route("/example").linkFunction((request) async {
      return Response.ok({"key": "value"});
    })
    ..route('/').linkFunction((request) => Response.ok({'name': '赵栋亮'}))
    ..route('/files/*').link(() => FileController('static/'))
    ..route('/files2/*').link(() => FileController(
          'static/',
          onFileNotFound: (controller, req) async {
            final file = File('static/timg.png');
            final byteStream = file.openRead();
            return Response.ok(
              byteStream,
            )
              ..encodeBody = false
              ..contentType = ContentType('image', 'jpeg');
          },
        )..addCachePolicy(
            const CachePolicy(expirationFromNow: Duration(days: 10)),
            //用于判断哪些图片或资源格式需要缓存
            (path) => path.endsWith('.jpg')))
    ..route('/user/register')
    // 添加该接口的客户端访问限制
        .link(() => Authorizer.basic(_authServer))
        .link(() => RegisterController(context, _authServer))
      //登录
    ..route('/auth/token').link(() => AuthController(_authServer))
    ..route('/articles/[:id]')
      .link(() => Authorizer.bearer(_authServer))
      .link(() => ArticleController(context));
      // uK4KxFzcfYuQHYuzX9WfOQHxlPjvheow
}

class ReadConfig extends Configuration {
  ReadConfig(String path) : super.fromFile(File(path));
  int port;
  DatabaseConfiguration database;
}